// ============================================================================
// E2E 测试全局设置
// ============================================================================

import { chromium, FullConfig } from '@playwright/test'
import path from 'path'
import fs from 'fs'

async function globalSetup(config: FullConfig) {
  console.log('🚀 开始E2E测试全局设置...')
  
  // 创建测试结果目录
  const testResultsDir = path.join(__dirname, '..', 'test-results')
  if (!fs.existsSync(testResultsDir)) {
    fs.mkdirSync(testResultsDir, { recursive: true })
  }
  
  // 创建截图目录
  const screenshotsDir = path.join(testResultsDir, 'screenshots')
  if (!fs.existsSync(screenshotsDir)) {
    fs.mkdirSync(screenshotsDir, { recursive: true })
  }
  
  // 创建视频目录
  const videosDir = path.join(testResultsDir, 'videos')
  if (!fs.existsSync(videosDir)) {
    fs.mkdirSync(videosDir, { recursive: true })
  }
  
  // 启动浏览器进行预热
  const browser = await chromium.launch()
  const context = await browser.newContext()
  const page = await context.newPage()
  
  try {
    // 预热应用
    console.log('🔥 预热应用...')
    await page.goto('http://localhost:3000', { waitUntil: 'networkidle' })
    
    // 等待应用完全加载
    await page.waitForSelector('[data-testid="app-loaded"]', { timeout: 30000 })
    
    console.log('✅ 应用预热完成')
  } catch (error) {
    console.warn('⚠️ 应用预热失败，但继续测试:', error)
  } finally {
    await context.close()
    await browser.close()
  }
  
  // 设置测试数据
  await setupTestData()
  
  console.log('✅ E2E测试全局设置完成')
}

/**
 * 设置测试数据
 */
async function setupTestData() {
  console.log('📊 设置测试数据...')
  
  // 这里可以设置测试所需的数据
  // 例如：创建测试账号、任务等
  
  const testData = {
    accounts: [
      {
        id: 'test-account-1',
        userInfo: {
          uid: '123456789',
          nickname: 'E2E测试账号1',
          avatar: 'https://example.com/avatar1.jpg',
          isVip: true,
          followersCount: 1000,
          followingCount: 500,
          statusesCount: 2000
        },
        isValid: true,
        cookies: 'test-cookies-1',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      },
      {
        id: 'test-account-2',
        userInfo: {
          uid: '987654321',
          nickname: 'E2E测试账号2',
          avatar: 'https://example.com/avatar2.jpg',
          isVip: false,
          followersCount: 500,
          followingCount: 300,
          statusesCount: 1000
        },
        isValid: false,
        cookies: 'test-cookies-2',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
    ],
    tasks: [
      {
        id: 'test-task-1',
        type: 'keyword_search',
        params: {
          keyword: 'E2E测试关键词',
          count: 100
        },
        status: 'completed',
        accountId: 'test-account-1',
        progress: {
          stage: 'completed',
          current: 100,
          total: 100,
          percentage: 100,
          message: '任务完成'
        },
        result: {
          totalCount: 95,
          successCount: 90,
          errorCount: 5
        },
        priority: 5,
        retryCount: 0,
        maxRetries: 3,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
    ],
    weiboData: Array.from({ length: 50 }, (_, i) => ({
      id: `test-weibo-${i + 1}`,
      weiboId: `wb_${Date.now()}_${i}`,
      text: `这是第${i + 1}条E2E测试微博内容`,
      userId: `user_${i}`,
      userNickname: `测试用户${i + 1}`,
      userAvatar: `https://example.com/avatar${i}.jpg`,
      source: '微博网页版',
      repostsCount: Math.floor(Math.random() * 100),
      commentsCount: Math.floor(Math.random() * 50),
      likesCount: Math.floor(Math.random() * 200),
      isRepost: Math.random() > 0.7,
      taskId: 'test-task-1',
      createdAt: new Date(Date.now() - Math.random() * 86400000 * 7).toISOString(),
      updatedAt: new Date().toISOString()
    }))
  }
  
  // 将测试数据保存到文件
  const testDataPath = path.join(__dirname, 'test-data.json')
  fs.writeFileSync(testDataPath, JSON.stringify(testData, null, 2))
  
  console.log('✅ 测试数据设置完成')
}

export default globalSetup
